import { StoreOptions, MutationTree, ActionTree } from 'vuex'
import { setToken, removeToken } from '/@/utils/auth'

export interface UserState {
  user: object,
  token: string
}

export default {
  namespaced: true,

  state: {
    user: {
      phone: 13888888888,
      id: 11111,
      username: '张三',
      age: 22,
      // 0：女， 1：男
      sex: 1,
    },
    token: ''
  },

  mutations: {
    SET_TOKEN (state, token: string) {
      state.token = token
    },
    SET_USER(state, params) {
      Object.assign(state.user, params)
    },
  } as MutationTree<UserState>,

  actions: {
    /**
     * 登录
     * @param param0 action
     * @param payload 参数
     */
    login({ commit }, payload) {
      const { username, password } = payload
      const res = { code: 0, message: '' }
      const token = 'asdfasdfas234234234234234'

      if (username === 'admin' && password === 'admin') {
        commit('SET_USER', payload)
        commit('SET_TOKEN', token)
        setToken(token)
      } else {
        res.code = 1
        res.message = '用户名密码错误'
      }

      return res
    },
    // 获取用户信息
    getUserInfo ({ state }) {
      return state.user
    },
    /**
     * 退出
     * @param param0 action
     */
    logOut({ commit }) {
      commit('SET_TOKEN', '')
      removeToken()
    },
  } as ActionTree<UserState, UserState>,
} as StoreOptions<UserState>
